<template>
    <div class="face-capture">
      <!-- 摄像头预览区域 -->
      <div class="camera-wrapper">
        <!-- 人脸框引导 -->
        <div class="face-guide">
          <div class="face-frame"></div>
          <p class="guide-text">请将脸部对准框内</p>
        </div>
        
        <!-- 视频预览 -->
        <video
          ref="videoRef"
          autoplay
          playsinline
          muted
          class="camera-preview"
          @loadedmetadata="onVideoLoaded"
        ></video>
        
        <!-- 用于捕获图像的画布（隐藏） -->
        <canvas ref="canvasRef" class="capture-canvas"></canvas>
      </div>
  
      <!-- 控制按钮 -->
      <div class="control-buttons">
        <el-button 
          @click="toggleCamera"
          size="large"
          class="switch-btn"
        ></el-button>
        
        <el-button 
          type="primary" 
          @click="captureImage"
          size="large"
          class="capture-btn"
          :loading="isCapturing"
        ></el-button>
        
        <el-button 
          @click="resetCapture"
          size="large"
          class="reset-btn"
        ></el-button>
      </div>
  
      <!-- 捕获结果预览 -->
      <div v-if="capturedImage" class="result-preview">
        <h3>捕获结果</h3>
        <img :src="capturedImage" alt="人脸图像" class="result-image">
        <el-button 
          type="success" 
          @click="confirmResult"
          size="small"
        >确认使用</el-button>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, onUnmounted, watch } from 'vue';
  import { ElMessage, ElLoading } from 'element-plus';
  
  // DOM 引用
  const videoRef = ref<HTMLVideoElement | null>(null);
  const canvasRef = ref<HTMLCanvasElement | null>(null);
  
  // 状态管理
  const isCameraActive = ref(false); // 摄像头是否激活
  const isCapturing = ref(false); // 是否正在捕获
  const capturedImage = ref(''); // 捕获的人脸图像
  const currentFacingMode = ref<'user' | 'environment'>('user'); // 当前摄像头（user：前置，environment：后置）
  let mediaStream: MediaStream | null = null;
  
  // 初始化摄像头
  const initCamera = async () => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      ElMessage.error('您的浏览器不支持摄像头调用');
      return;
    }
  
    try {
      // 停止已有流
      if (mediaStream) {
        mediaStream.getTracks().forEach(track => track.stop());
      }
  
      // 调用摄像头（手机端优先前置摄像头）
      mediaStream = await navigator.mediaDevices.getUserMedia({
        video: {
          facingMode: currentFacingMode.value,
          width: { ideal: 720 }, // 理想宽度
          height: { ideal: 1280 }, // 理想高度（适配手机竖屏）
          frameRate: { ideal: 30 } // 帧率
        }
      });
  
      if (videoRef.value) {
        videoRef.value.srcObject = mediaStream;
        isCameraActive.value = true;
      }
    } catch (error) {
      console.error('摄像头调用失败:', error);
      ElMessage.error('请授予摄像头权限或检查设备是否支持');
      isCameraActive.value = false;
    }
  };
  
  // 视频加载完成回调
  const onVideoLoaded = () => {
    if (videoRef.value && canvasRef.value) {
      // 设置画布尺寸与视频一致
      canvasRef.value.width = videoRef.value.videoWidth;
      canvasRef.value.height = videoRef.value.videoHeight;
    }
  };
  
  // 切换前后摄像头
  const toggleCamera = () => {
    currentFacingMode.value = currentFacingMode.value === 'user' ? 'environment' : 'user';
    initCamera();
  };
  
  // 捕获人脸图像
  const captureImage = async () => {
    if (!videoRef.value || !canvasRef.value || !isCameraActive.value) return;
  
    isCapturing.value = true;
    const loading = ElLoading.service({ text: '正在捕获图像...' });
  
    try {
      // 绘制当前视频帧到画布
      const ctx = canvasRef.value.getContext('2d');
      if (ctx) {
        ctx.drawImage(
          videoRef.value,
          0, 0,
          canvasRef.value.width,
          canvasRef.value.height
        );
        // 转为 base64 格式（可根据需求调整格式和质量）
        capturedImage.value = canvasRef.value.toDataURL('image/jpeg', 0.8);
        ElMessage.success('人脸图像捕获成功');
      }
    } catch (error) {
      console.error('图像捕获失败:', error);
      ElMessage.error('图像捕获失败，请重试');
    } finally {
      isCapturing.value = false;
      loading.close();
    }
  };
  
  // 重置捕获状态
  const resetCapture = () => {
    capturedImage.value = '';
    if (!isCameraActive.value) {
      initCamera(); // 如果摄像头已关闭，重新打开
    }
  };
  
  // 确认使用捕获的图像
  const confirmResult = () => {
    if (capturedImage.value) {
      // 这里可以将图像数据传递给父组件或进行后续处理
      ElMessage.success('已确认使用该人脸图像');
      
      // 示例：触发回调（需在父组件中监听）
      // emit('confirm', capturedImage.value);
    }
  };
  
  // 组件挂载时初始化摄像头
  onMounted(() => {
    initCamera();
  });
  
  // 组件卸载时释放资源
  onUnmounted(() => {
    if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop());
      mediaStream = null;
    }
  });
  
  // 监听摄像头状态变化
  watch(isCameraActive, (newVal) => {
    if (!newVal) {
      capturedImage.value = ''; // 摄像头关闭时清空结果
    }
  });
  </script>
  
  <style scoped>
  .face-capture {
    max-width: 400px;
    margin: 0 auto;
    padding: 16px;
  }
  
  /* 摄像头容器 */
  .camera-wrapper {
    position: relative;
    width: 100%;
    /* 16:9 竖屏比例（手机常用） */
    padding-top: 177.78%; /* 9/16 = 0.5625 → 竖屏反转为 16/9 ≈ 1.7778 */
    border-radius: 16px;
    overflow: hidden;
    background-color: #000;
  }
  
  /* 视频预览 */
  .camera-preview {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  /* 人脸引导框 */
  .face-guide {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }
  
  .face-frame {
    width: 200px;
    height: 250px;
    border: 2px solid rgba(255, 255, 255, 0.8);
    border-radius: 20px;
    position: relative;
  }
  
  .face-frame::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 160px;
    height: 210px;
    border: 1px dashed rgba(255, 255, 255, 0.5);
    border-radius: 16px;
  }
  
  .guide-text {
    color: white;
    margin-top: 20px;
    font-size: 14px;
    text-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  }
  
  /* 隐藏的画布 */
  .capture-canvas {
    display: none;
  }
  
  /* 控制按钮区域 */
  .control-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 40px;
    margin: 30px 0;
  }
  
  .switch-btn, .reset-btn {
    background-color: rgba(255, 255, 255, 0.8);
    color: #333;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .capture-btn {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 10px rgba(64, 158, 255, 0.4);
  }
  
  /* 结果预览 */
  .result-preview {
    margin-top: 20px;
    text-align: center;
  }
  
  .result-image {
    max-width: 100%;
    border-radius: 8px;
    margin: 10px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  </style>